package com.hw.dagl.service.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hw.dagl.model.Dagl_T_Audit;
import com.hw.dagl.model.Sys_Role;
import com.hw.dagl.model.Sys_User;
import com.hw.dagl.service.IAuditService;
import com.hw.dao.utils.EntityTools;
import com.hw.dao.utils.OraclePageDaoBase;
import com.hw.dao.utils.OraclePageDaoBase1;
import com.hw.dao.utils.Page;
import com.hw.interceptor.SystemLog;
import com.hw.utils.StringUtils;

@Service("auditService")
public class AuditServiceImpl implements IAuditService {
    
    private Logger logger=LoggerFactory.getLogger(AuditServiceImpl.class);

    @Resource
    private OraclePageDaoBase oraclepagedaobase;
    @Resource
    private OraclePageDaoBase1 oraclePageDaoBase1;
    
    @Override
    public Page<Dagl_T_Audit> queryAuditByPage(Page<Dagl_T_Audit> page, Dagl_T_Audit dagl_T_Audit, String startTime,
            String endTime,Sys_Role sysRole,String operatorType) {
        //根据角色切换数据源
        //oraclepagedaobase.setSourceByRole(sysRole);
        List<String> paramList =new ArrayList<String>();
        StringBuilder sql=new StringBuilder(" select applyNo,hphm,applicant,applyDate,applicantbmbm,applicantbmmc,to_char(applyDate,'yyyy-MM-dd hh24:mi:ss') as strApplyDate,"
                + "sfzmhm,permissionType,decode(permissionType,01,'打印权限','02','下载权限','03','删除权限') as strPermission,"
                + "zt,decode(zt,2,'审核不通过',0,'待审核',1,'审核通过') as strZt,xh,lsh,ywlx from dagl_T_Audit where 1=1 ");
        if(StringUtils.isNotEmpty(startTime)){
            sql.append(" and applydate>=to_date(?,'yyyy-MM-dd hh24:mi:ss') ");
            paramList.add(startTime);
        }
        if(StringUtils.isNotEmpty(endTime)){
            sql.append(" and applydate<=to_date(?,'yyyy-MM-dd hh24:mi:ss') ");
            paramList.add(endTime);
        }
        //权限类型
        String permissionType=dagl_T_Audit.getPermissionType();
        if(StringUtils.isNotEmpty(permissionType)){
            sql.append(" and permissionType=?" );
            paramList.add(permissionType);
        }
        
        //申请人
        String applicant = dagl_T_Audit.getApplicant();
        if(null == operatorType && StringUtils.isNotEmpty(applicant)){
            sql.append(" and applicant =? " );
            paramList.add(applicant);
        }
        		
        String zt=dagl_T_Audit.getZt();
        if(StringUtils.isNotEmpty(zt)){
            sql.append(" and zt =? " );
            paramList.add(zt);
        }
        String lsh =dagl_T_Audit.getLsh();
        if(StringUtils.isNotEmpty(lsh)){
            sql.append(" and instr(lsh,?) >0 " );
            paramList.add(lsh);
        }
        sql.append(" and flag =? ");
        paramList.add("1");
        sql.append(" order by zt,applydate desc ");
        Page<Dagl_T_Audit> pages=null;
        //否则访问本地库
        pages=oraclepagedaobase.queryForPage(sql.toString(),page,new RowMapper<Dagl_T_Audit>() {
            private EntityTools<Dagl_T_Audit> et = new EntityTools<Dagl_T_Audit>();
            @Override
            public Dagl_T_Audit mapRow(ResultSet arg0, int arg1) throws SQLException {
                Dagl_T_Audit veh = new Dagl_T_Audit();
                et.setColumnsValueByResultSet(arg0, veh);
                return veh;
            }
        },paramList.toArray());
        return pages;
    }
    
   

    @Override
    @Transactional(readOnly=false,rollbackFor=Exception.class)
    public Integer addAudit(Dagl_T_Audit dagl_T_Audit) {
       String applicant=dagl_T_Audit.getApplicant();
       String applicantBmbm=dagl_T_Audit.getApplicantBmbm();//申请人所在部门编码
       String applicantBmmc=dagl_T_Audit.getApplicantBmmc();//申请人所在部门名称
       String hphm=dagl_T_Audit.getHphm();
       String permissionType=dagl_T_Audit.getPermissionType();//权限类型  01 删除权限  02  下载权限  03 打印权限
       String hpzl=dagl_T_Audit.getHpzl();//号牌种类
       String bz=dagl_T_Audit.getBz();//备注(申请原因)
       String xh=dagl_T_Audit.getXh();
       String lsh=dagl_T_Audit.getLsh();
       String ywlx=dagl_T_Audit.getYwlx();
       String sql=" insert into  dagl_T_Audit (applyno,applicant,applicantBmbm,applicantBmmc,applydate, "
           +"permissionType,hphm,zt,hpzl,bz,xh,lsh,ywlx) values(seq_backup.Nextval,?,?,?,sysdate,?,?,?,?,?,?,?,?) ";
       logger.info("新增授权申请sql "+sql);
       Integer num=oraclepagedaobase.update(sql,new Object[]{applicant,applicantBmbm,applicantBmmc,permissionType,hphm,"0",hpzl,bz,xh,lsh,ywlx});
      return num;
    }

    //批量审核或者单个审核
    @Override
    @Transactional(readOnly=false,rollbackFor=Exception.class)
    public Integer editAudit(Dagl_T_Audit dagl_T_Audit) {
          String applyNo=dagl_T_Audit.getApplyNo();
          String[] arrApplyNo=applyNo.split(",");
          int length=arrApplyNo.length;
          String[] sqlArr =new String[length]; 
          for(int i=0;i<length;i++){
              StringBuilder stringBuilder=new StringBuilder(" update dagl_T_Audit");
              String auditor=dagl_T_Audit.getAuditor();//审核人
              if(null!=auditor){
                  stringBuilder.append(" set auditor='"+auditor+"',");
              }
              String auditorBmbm=dagl_T_Audit.getAuditorBmbm();//审核人所在部门编码
              if(null!=auditorBmbm){
                  stringBuilder.append(" auditorBmbm='"+auditorBmbm+"',");
              }
              String auditorBmmc=dagl_T_Audit.getAuditorBmmc();//审核人所在部门名称
              if(null!=auditorBmmc){
                  stringBuilder.append(" auditorBmmc='"+auditorBmmc+"',");
                  stringBuilder.append(" auditDate=sysdate, ");
              }
              String zt=dagl_T_Audit.getZt();//状态
              if(null!=zt){
                  stringBuilder.append(" zt='"+zt+"'");
              }
              int downloadNum =dagl_T_Audit.getDownloadNum();//下载次数
              if(downloadNum>0){
                  stringBuilder.append(" set downloadNum="+downloadNum+" ");
              }
              int printNum=dagl_T_Audit.getPrintNum();//打印次数
              if(printNum>0){
                  stringBuilder.append(" set printNum="+printNum+" ");
              }
            
              stringBuilder.append(" where applyNo='"+arrApplyNo[i]+"' ");
              sqlArr[i]=stringBuilder.toString();
          }
          int[] num=oraclepagedaobase.batchUpdate(sqlArr);
          return num[0];
    }
    
    

    @Override
    @SystemLog(Modelname="权限申请",operationType="2",operationName="批量下载档案")
    public Dagl_T_Audit queryAuditByHphm(Dagl_T_Audit dagl_T_Audit) {
        List<String> paramList=new ArrayList<String>();
        StringBuilder sql=new StringBuilder("select * from dagl_T_Audit where 1=1 ");
        String hphm=dagl_T_Audit.getHphm();
        //号牌号码
        if(StringUtils.isNotEmpty(hphm)){
            sql.append(" and hphm=? ");
            paramList.add(hphm);
        }
        //号牌种类
        String hpzl=dagl_T_Audit.getHpzl();
        if(StringUtils.isNotEmpty(hpzl)){
            sql.append(" and hpzl=? ");
            paramList.add(hpzl);
        }
        //申请人
        String applicant=dagl_T_Audit.getApplicant();
        if(StringUtils.isNotEmpty(applicant)){
            sql.append(" and applicant=?  ");
            paramList.add(applicant);
        }

        //权限类型  01:打印 02:下载  03:删除
        String permissionType=dagl_T_Audit.getPermissionType();
        if(StringUtils.isNotEmpty(permissionType)){
            sql.append(" and permissionType=?  ");
            paramList.add(permissionType);
        }

        //流水号
        String lsh=dagl_T_Audit.getLsh();
        if(StringUtils.isNotEmpty(lsh)){
            sql.append(" and lsh=?  ");
            paramList.add(lsh);
        }
        
      //序号
        String xh=dagl_T_Audit.getXh();
        if(StringUtils.isNotEmpty(xh)){
            sql.append(" and xh=?  ");
            paramList.add(xh);
        }
        
        sql.append(" and flag=?  ");
        paramList.add("1");

        List<Dagl_T_Audit> dagl_T_Audits=oraclepagedaobase.query(sql.toString(),paramList.toArray(),new BeanPropertyRowMapper<Dagl_T_Audit>(Dagl_T_Audit.class));
        logger.info("判断是否已申请某个权限的sql  "+sql.toString());
        if(dagl_T_Audits.size()>0){
            dagl_T_Audit=dagl_T_Audits.get(0);
        }else{
            dagl_T_Audit=null;
        }
        return dagl_T_Audit;
    }

    @Override
    public Dagl_T_Audit queryAuditByApplyNo(Dagl_T_Audit dagl_T_Audit) {
        String applyNo=dagl_T_Audit.getApplyNo();
        String sql="select applyNo,to_char(applyDate,'yyyy-MM-dd hh24:mi:ss') as strApplyDate"
                + ",applicant,applicantBmmc,auditor,auditorBmmc,"
                + "to_char(auditDate,'yyyy-MM-dd hh24:mi:ss') as strAuditDate,"
                + "decode(zt,2,'审核不通过',0,'待审核',1,'审核通过') as strZt,downloadNum,printNum from dagl_T_Audit where applyNo=? ";
        List<Dagl_T_Audit> dagl_T_Audits=oraclepagedaobase.query(sql.toString(),new Object[]{applyNo},new BeanPropertyRowMapper<Dagl_T_Audit>(Dagl_T_Audit.class));
        if(dagl_T_Audits.size()>0){
            dagl_T_Audit=dagl_T_Audits.get(0);
        }else{
            dagl_T_Audit=null;
        }
        return dagl_T_Audit;
    }

    @Override
    public List<Dagl_T_Audit> queryAuditByList(Dagl_T_Audit dagl_T_Audit) {
        List<String> paramList=new ArrayList<String>();
        StringBuilder sql=new StringBuilder("select permissionType,applyNo from dagl_T_Audit where 1=1");
        String applicant=dagl_T_Audit.getApplicant();
        if(StringUtils.isNotEmpty(applicant)){
            sql.append(" and applicant=?");
            paramList.add(applicant);
        }
        String hphm=dagl_T_Audit.getHphm();//号牌号码
        if(StringUtils.isNotEmpty(hphm)){
        	hphm="皖"+hphm;
            sql.append(" and hphm=?");
            paramList.add(hphm);
        }
        String hpzl=dagl_T_Audit.getHpzl();//号牌号码
        if(StringUtils.isNotEmpty(hpzl)){
            sql.append(" and hpzl=?");
            paramList.add(hpzl);
        }

        String lsh=dagl_T_Audit.getLsh();
        if(StringUtils.isNotEmpty(lsh)){
            sql.append(" and lsh=?");
            paramList.add(lsh);
        }
        
        String xh=dagl_T_Audit.getXh();
        if(StringUtils.isNotEmpty(xh)){
        	sql.append(" and xh=?");
            paramList.add(xh);
        }

        sql.append(" and zt='1' and flag='1' ");
        logger.info("查询权限信息的sql  "+sql  +"sh=" +xh+  "hpzl= "+hpzl+ "applicant="+applicant);
        List<Dagl_T_Audit> dagl_T_Audits=oraclepagedaobase.query(sql.toString(),paramList.toArray(),new BeanPropertyRowMapper<Dagl_T_Audit>(Dagl_T_Audit.class));
        return dagl_T_Audits;
    }



    @Override
    @Transactional(readOnly=false,rollbackFor=Exception.class)
    public Integer updateAuditFlag(Dagl_T_Audit dagl_T_Audit, Sys_User user) {
        StringBuilder sql = new StringBuilder("update dagl_T_Audit SET flag='0' WHERE lsh=? AND xh=? and applicant=? ");
        List<String> paramList = new ArrayList<String>();
        String lsh = dagl_T_Audit.getLsh();//流水号
        paramList.add(lsh);
        String xh =dagl_T_Audit.getXh();//序号
        paramList.add(xh);
        String applicant = user.getYhdh();
        paramList.add(applicant);
        int num = oraclepagedaobase.update(sql.toString(), paramList.toArray());
        return num;
    }

}
